package com.ts.api.http.sms;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.Base64Utils;
import com.gitee.apanlh.util.log.Log;
import com.gitee.apanlh.util.log.LogLevel;
import com.gitee.apanlh.util.net.http.HttpClientBuilder;
import com.gitee.apanlh.util.net.http.HttpResponse;
import com.gitee.apanlh.web.http.HttpMethod;
import com.ts.api.module.log.dao.SmsLogDao;
import com.ts.api.module.log.entity.SmsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *  玄武云短信-安心分期
 *
 *  @author Pan
 */
@Component
public class XwySmsProvider implements SmsProvider {

    private static final String ACCOUNT = "szhh@szhh";
    private static final String PWD = "91ub08LI";

    @Autowired
    private SmsLogDao smsLogDao;

    @Override
    public void sendCode(String phone, String code) {
        String msg = "尊敬的用户，您本次的验证码为" + code + "，有效期3分钟。防诈骗提示：一切境外电话、以交纳手续费、保证金、解冻费等名义要求转账的都是诈骗！";
        String smsType = "发送短信验证码";
        sendSms(ACCOUNT, PWD, phone, msg, smsType);
    }

    @Override
    public void sendCustomerNotice(String phone, String orgName) {
        String msg = "尊敬的用户，\"" + orgName + "\"已收到您的申请，办理前请注意核实对方信息，业务员预计1小时内联系您，请保持手机畅通！防诈骗提示：一切港澳台电话、QQ咨询转账都是诈骗行为！";
        String smsType = "发送客户营销短信";
        Thread.ofVirtual().start(() -> sendSms(ACCOUNT, PWD, phone, msg, smsType));
    }

    @Override
    public void sendCustomerNoticeForIpOffModule(String phone, String orgName) {
        String msg = "尊敬的用户，我们已收到您的申请，业务员预计1小时内联系您，请保持手机畅通！防诈骗提示：一切境外电话，QQ联系转账都是诈骗行为！";
        String smsType = "发送客户营销短信（用于Ip屏蔽）";
        Thread.ofVirtual().start(() -> sendSms(ACCOUNT, PWD, phone, msg, smsType));
    }

    @Override
    public void sendCrmNotice(String phone, String orgName) {
        String msg = "" + orgName + "，您有新的用户申请，请及时查收。";
        String smsType = "发送crm人员短信通知";
        Thread.ofVirtual().start(() -> sendSms(ACCOUNT, PWD, phone, msg, smsType));
    }

    /**
     *  发送短信消息
     *
     *  @param account 账号
     *  @param pwd     密码
     *  @param phone   手机号
     *  @param msg     消息
     */
    void sendSms(String account, String pwd, String phone, String msg, String smsType) {
        String status = "1";
        //  发送开始时间
        long start = System.currentTimeMillis();
        //  请求头
        Map<String, String> headers = MapUtils.newHashMap();
        //  响应数据
        String str = "";
        Map<String, Object> bodyMap = MapUtils.newHashMap();

        Map<String, String> item = MapUtils.newHashMap(itemMap -> itemMap.put("to", phone));
        List<Map<String, String>> items = CollUtils.newArrayList(itemsList -> itemsList.add(item));
        bodyMap.put("items", items);
        bodyMap.put("content", msg);
        bodyMap.put("msgType", "sms");
        //  接收数据
        String reqJson = JSONObject.toJSONString(bodyMap);

        try {
            HttpResponse build = HttpClientBuilder.builder("http://sh.mosapi.cn:9051/api/v1.0.0/message/mass/send", HttpMethod.POST)
                    .withBodyJson(reqJson)
                    .withHeader((headerMap) -> {
                        String authorization = Base64Utils.encodeToStr(account + ":" + MD5.create().digestToHex(pwd));
                        headerMap.put("Content-Type", "application/json;charset=utf-8");
                        headerMap.put("Accept", "application/json");
                        headerMap.put("Authorization", authorization);

                        // 保存请求头
                        headers.putAll(headerMap);
                    })
                    .withLogLevel(LogLevel.WARN)
                    .withErrorLogLevel(LogLevel.WARN)
                    .build();
            if (build.isError()) {
                status = "0";
                Log.get().warn("通知短信发送异常:{}", build.getErrorMsg());
                return;
            }

            str = build.getStr();
            JSONObject jsonObject = JSONObject.parseObject(str);
            if (jsonObject == null || jsonObject.getInteger("code") != 0) {
                status = "0";
                Log.get().warn("通知短信发送失败, 手机号:[{}], 响应体:{}", phone, str);
            }

        } catch (Exception e) {
            status = "0";
            throw e;
        } finally {
            //  发送结束结束
            long end = System.currentTimeMillis();
            //  创建短信日志实体类
            SmsLog smsLog = new SmsLog();
            //  手机号
            smsLog.setPhone(phone);
            //  服务商名称
            smsLog.setProviderName("玄武云");
            //  短信类型（如验证码、通知等）
            smsLog.setType(smsType);
            //  状态 0：失败 1：成功
            smsLog.setStatus(status);
            //  短信内容
            smsLog.setContext(msg);
            //  请求地址
            smsLog.setReqUrl("http://sh.mosapi.cn:9051/api/v1.0.0/message/mass/send");
            //  请求头
            smsLog.setReqHeader(JsonUtils.toJson(headers));
            //  接收数据
            smsLog.setReqData(reqJson);
            //  响应数据
            smsLog.setRespData(str);
            //  耗时毫秒数
            smsLog.setTaskTime(end - start);
            //  创建时间
            smsLog.setCreateTime(new Date());

            smsLogDao.insert(smsLog);
        }
    }
}
